Component({
  externalClasses: ['custom-class'],
  properties: {
    category: {
      type: Array,
    },
    initActive: {
      type: Array,
      value: [],
      observer(newVal, oldVal) {
        if (newVal[0] !== oldVal[0]) {
          this.setActiveKey(newVal[0], 0);
        }
      },
    },
    isSlotRight: {
      type: Boolean,
      value: false,
    },
    level: {
      type: Number,
      value: 3,
    },
  },
  data: {
    activeTab: 0, // 当前点击的锚点tab
    activeKey: 0,
    subActiveKey: 0,

    goodsNum:'', // 
    viewid: 'cont0',

    showSelect: false,
    currentGg: {}, // 选规格弹框：当前选择的规格 .name 名称 .children 子数组
    currentCheck: [], // 选规格弹框：选择的结果
    currentCheckName: [], // 选规格弹框：选择的结果中文数组
    currentRemark: '', // 选规格弹框：填写的备注
    selectAll: false,

    showSelectUnit: false, // 是否显示选择单位下拉框
    unitlist: [],
    tagList: [{num: 3}, {num: 5}, {type: 'success', num: 10}, {type: 'danger', num: 15}, {type: 'warning', num: 20}]
  },
  computed: {
    // sum: function() {
    //   return this.data.num1 + this.data.num2
    // }
  },
  methods: {
    onShowSelectUnit(event) {
      const { unitlist } = event.currentTarget.dataset;
      console.log('1', unitlist);
      if(unitlist.length) {
        this.setData({ showSelectUnit: true, unitlist });
      }
    },
    onCloseSelectUnit() {
      this.setData({ showSelectUnit: false });
    },
    // 更改锚点跳转id和选中tab
    setViewidAndActiveTab(viewid, activeTab) {
      this.setData({ viewid, activeTab })
    },
    // 左侧tab改变时
    onParentChange(event) {
      this.setActiveKey(event.detail.index, 0).then(() => {
        // this.triggerEvent('change', [
        //   this.data.activeKey,
        //   this.data.subActiveKey,
        // ]);
      });
      // 页面获取自定义组件实例，并使其重新渲染
      this.selectComponent('#goods-tab').reRenderTab();
      // 切换左侧tab，重置右侧二级tab
      this.setViewidAndActiveTab('cont0', 0)
    },
    // 点击tab时
    getViewId(name) {
      // console.log(name)
      this.setViewidAndActiveTab("cont" + name.detail, name.detail)
    },
  // 加法
    addtion(event) {
      const { item, subitem, index, subindex } = event.currentTarget.dataset;
      let num = event.currentTarget.dataset.num;
      const { activeKey } = this.data;
      if (num < 99) num++
      console.log(item, subitem, index, subindex);
      this.triggerEvent('changeCategory', {
        num,
        activeKey, // 左侧选中的tab
        index,  // 当前tab下的第几个小分类
        subindex, // 当前小分类的第几个
        // data: [subitem],
        // subitem,
      });
    },
    // 当用户输入时，存储输入的数字
    inputNum(event){
      // console.log(event.detail.value);
      this.setData({
        goodsNum: event.detail.value //
      })
    },
    // 当用户聚焦时，存储输入的数字
    numIputFocus(event){
      console.log('聚焦', event.detail.value);
      this.setData({
        goodsNum: event.detail.value //
      })
    },
    numIputBlur(event){
      const { index, subindex } = event.currentTarget.dataset;
      const { activeKey } = this.data;
      let num = this.data.goodsNum;
      if (num == ''){
        num = 1
      } else if (num < 1){
        num = 1
      } else if (num > 99){
        num = 1
      }
      this.triggerEvent('changeCategory', {
        num,
        activeKey, // 左侧选中的tab
        index,  // 当前tab下的第几个小分类
        subindex,
      });
    },
    //减法
    subtraction(event) {
      const { item, subitem, index, subindex } = event.currentTarget.dataset;
      let num = event.currentTarget.dataset.num;
      const { activeKey } = this.data;
      if (num == 1) {//当数量为1件时，再次点击移除该商品
        num = 0
      } else {
        num--
      }
      console.log(item, subitem, index, subindex);
      this.triggerEvent('changeCategory', {
        num,
        activeKey, // 左侧选中的tab
        index,  // 当前tab下的第几个小分类
        subindex,
      });
    },


    getCurrent(subitem) {
      const currentCheck = subitem.children.filter(i => i.num > 0)
      const currentCheckName = currentCheck.map(i => i.name)
      const currentRemark = subitem.remark;
      return { currentRemark, currentCheck, currentCheckName }
    },
    setCurrent(newCurrentGg) {
      const { currentRemark, currentCheck, currentCheckName } = this.getCurrent(newCurrentGg)
      console.log(newCurrentGg, currentCheck, currentCheckName);
      this.setData({
        currentGg: newCurrentGg,
        currentCheck,
        currentCheckName,
        currentRemark,
      });
    },
    // 父组件点选择
    chooseCategoryByParent(subitem) {
      console.log(subitem);
      this.setCurrent(subitem)
      this.setData({ showSelect: true });
    },
    // 点击选择时，
    chooseCategory(event) {
      const { subitem } = event.currentTarget.dataset;
      this.setCurrent(subitem)
      this.setData({ showSelect: true });
    },
    // 全选或取消全选
    selectOrUnselectAll() {
      let newCurrentGg = this.data.currentGg;
      newCurrentGg.children.forEach(child => {
        if (this.data.selectAll){
          child.num = 0;
        } else {
          child.num = child.num || 1;
        }
      })
      this.setCurrent(newCurrentGg)
      this.setData({
        selectAll: !this.data.selectAll,
      });
    },
    onChangeCheck(event) {
      console.log(event.detail);
      let newCurrentGg = this.data.currentGg;
      newCurrentGg.children.forEach(child => {
        if (event.detail.includes(child.name)){
          child.num = child.num || 1;
        } else {
          child.num = 0
        }
      })
      this.setCurrent(newCurrentGg)
    },
    onChangeStep(event) {
      const { item } = event.currentTarget.dataset;
      let newCurrentGg = this.data.currentGg;
      newCurrentGg.children.forEach(child => {
        if (item.name === child.name){
          child.num = event.detail;
        }
      })
      this.setCurrent(newCurrentGg)
    },
    onClickTag(event) {
      // console.log(event);
      const { item, num, btnType, index, subindex } = event.detail;
      console.log(event.detail);
      if (btnType === "group") {
        // const { item, subitem, index, subindex } = event.currentTarget.dataset;
        const { activeKey } = this.data;
        // console.log(item, subitem, index, subindex);
        this.triggerEvent('changeCategory', {
          num,
          activeKey, // 左侧选中的tab
          index,  // 当前tab下的第几个小分类
          subindex, // 当前小分类的第几个
        });
      } else {
        let newCurrentGg = this.data.currentGg;
        newCurrentGg.children.forEach(child => {
          if (item.name === child.name){
            child.num = num;
          }
        })
        this.setCurrent(newCurrentGg)
      }
    },
    // 确认选择
    onConfirm() {
      const { currentRemark, currentGg, currentCheck } = this.data;
      const { index, subindex, activeKey } = currentGg;
      const num = currentGg.children.reduce((acc, cur) => acc + cur.num, 0)
      console.log('currentRemark', currentRemark);

      let newCurrentGg = {
        ...currentGg,
        num,
      }
      this.setData({
        showSelect: false,
        currentGg: newCurrentGg,
      });
      // console.log(num, index, subindex);

      let obj = {
        num,
        activeKey, // 左侧选中的tab
        index,  // 当前tab下的第几个小分类
        subindex,
      }
      if (currentGg.btnType === 'btn' ){
        const newCurrentCheckName = currentCheck.map(i => {
          return i.name + i.num + currentGg.unit
        })
// 额外的名字由：1.选择的口味个数 2.备注 两部分组成
        const extraName = '：' + newCurrentCheckName.join('，') // 额外名字
        obj.children = currentGg.children;
        obj.extraName = currentRemark ? extraName + '(' + currentRemark + ')' : extraName;
        obj.remark = currentRemark;
      }
      this.triggerEvent('changeCategory', obj);
    },
    // 当弹框关闭时
    onClose() {
      // console.log('gb');
      this.setData({
        showSelect: false,
        selectAll: false,
        currentGg: {}, // 当前选择的规格 .name 名称 .children 子数组
        currentCheck: [], // 选择的结果
        currentCheckName: [],
        currentRemark: '',
      });
    },

    // 点击图片预览
    previewImage(event) {
      const { index, subindex } = event.currentTarget.dataset;
      const { category, activeKey } = this.data;
      // 获取左侧tab对应的数组
      const child = category[activeKey].children;
      // 获取当前tab需要展示所有分类的图片
      const children = child.map(i => i.children); // children: [ [{thumbnail: ''}], [{thumbnail: ''}] ]
      const { flatChildren, flatBeforeChildren, flatNowchildren } = this.getChildren(children, index)

      const imgs = flatChildren.map(i => i.thumbnail);
      // 看看当前分类的图片有没有隐藏的
      let imgIndex = flatBeforeChildren.length + subindex;
      flatNowchildren.forEach((i, n) => {
        if (i.showImg === false && n <= subindex){
          imgIndex--;
        }
      })
      console.log('imgIndex', imgIndex, flatNowchildren);
      wx.previewImage({
        urls: imgs,
        current: imgs[imgIndex]
      })
    },
    getChildren(children, index) {
      const flatChildren = children.flat().filter(i => i.showImg !== false);
      const beforeChildren = children.slice(0, index);
      const nowChildren = children.slice(index);
      const flatBeforeChildren = beforeChildren.flat().filter(i => i.showImg !== false);
      const flatNowchildren = nowChildren.flat();
      return {
        flatChildren,
        flatBeforeChildren,
        flatNowchildren
      }
    },
    setActiveKey(key, subKey) {
      return new Promise((resolve) => {
        this.setData(
          {
            activeKey: key,
            subActiveKey: subKey,
          },
          () => {
            resolve();
          },
        );
      });
    },
  },


  // attached() {
  //   if (this.properties.initActive && this.properties.initActive.length > 0) {
  //     this.setData({
  //       activeKey: this.properties.initActive[0],
  //       subActiveKey: this.properties.initActive[1] || 0,
  //     });
  //   }
  // },
  // // 暂时没用到
  // onChildChange(event) {
  //   this.setActiveKey(this.data.activeKey, event.detail.index).then(() => {
  //     this.triggerEvent('change', [
  //       this.data.activeKey,
  //       this.data.subActiveKey,
  //     ]);
  //   });
  // },
});
